/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.joinus.system_logger;

import br.ufes.cwtools.joinus.home.Home2;
import br.ufes.cwtools.joinus.home.SimpleProfileActivity;
import br.ufes.cwtools.joinus.util.ServerCom;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import br.ufes.cwtools.joinus.R;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class SystemLogger extends Activity {
	private EditText userField;
	private EditText passField;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		
		ServerCom.initResources(getResources());
		setContentView(R.layout.systemlogger);

		passField = (EditText) findViewById(R.id.passwordField);
		userField = (EditText) findViewById(R.id.usernameField);
		CheckBox remember = (CheckBox) findViewById(R.id.rememberme);

		SharedPreferences pref = getPreferences(0);
		userField.setText(pref.getString("user", ""));
		passField.setText(pref.getString("pass", ""));
		remember.setChecked(pref.getBoolean("remember", false));
		
		userField.setOnKeyListener(Util.filterAlphanumericOnKeyListener);
		passField.setOnKeyListener(Util.filterAlphanumericOnKeyListener);
	}
	
	private void launchMainActivity() {
		String username = userField.getText().toString().toLowerCase();
		String password = passField.getText().toString().toLowerCase();
		Intent intent = new Intent();
		intent.putExtra("un", username);
		intent.putExtra("pw", password);
		intent.setClass(this, Home2.class);
		Toast.makeText(this, "Starting application...", Toast.LENGTH_LONG).show();
		startActivity(intent);
	}

	private boolean isValidUsername(String username) {
		if (username.length() < 1) {
			Toast.makeText(this, "Please enter a user name.", Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}
	
	private boolean isValidPassword(String password) {
		if (password.length() < 5) {
			Toast.makeText(this, "The password should contain at least 5 characters.", Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}
	
	/**
	 * Método onClick para o botão de confirmação (login).
	 * @param view
	 */
	public void okOnClick(View view) {
		String username = userField.getText().toString().toLowerCase();
		String password = passField.getText().toString().toLowerCase();
		if (!isValidUsername(username) || !isValidPassword(password)) {
			return;
		}
		
		int response = ServerCom.authUser(username, password, username);
		if (response == ServerCom.SERVER_ERROR) {
			Toast.makeText(this, "There was an unknown error in the server.", Toast.LENGTH_LONG).show();
		} else if (response == ServerCom.INVALID_USER) {
			Toast.makeText(this, "Bad user name or password", Toast.LENGTH_LONG).show();
		} else if (response == ServerCom.SSL_ERROR) {
			Toast.makeText(this, "There was an unknown error on stablishing a secure connection.", Toast.LENGTH_LONG).show();
		} else {
			CheckBox remember = (CheckBox) findViewById(R.id.rememberme);
			if (remember.isChecked()) {
				SharedPreferences pref = getPreferences(MODE_PRIVATE);
				pref.edit().putString("user", username).commit();
				pref.edit().putString("pass", password).commit();
				pref.edit().putBoolean("remember", true).commit();;
			}
			launchMainActivity();
		}
	}
	
	static final int REQUEST_CREATE = 1;
	static final int REQUEST_EDIT_PROFILE = 2;
	
	/**
	 * Método onClick para o botão de criar nova conta.
	 * @param view
	 */
	public void createOnClick(View view) {
		String username = userField.getText().toString().toLowerCase();
		String password = passField.getText().toString().toLowerCase();
		if (!isValidUsername(username) || !isValidPassword(password)) {
			return;
		}
		
		Intent intent = new Intent();
		intent.putExtra("password", password);
		intent.setClass(this, PasswordConfirmationActivity.class);
		startActivityForResult(intent, REQUEST_CREATE);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CREATE && resultCode == RESULT_OK) {
			String username = userField.getText().toString().toLowerCase();
			String password = passField.getText().toString().toLowerCase();

			int serverResponse;
			if ((serverResponse = ServerCom.createUser(username, password, username, "<>")) == ServerCom.OK) {
				int response = ServerCom.authUser(username, password, username);
				if (response == ServerCom.SERVER_ERROR) {
					Toast.makeText(this, "There was an unknown error in the server.", Toast.LENGTH_LONG).show();
				} else if (response == ServerCom.INVALID_USER) {
					Toast.makeText(this, "Bad user name or password.", Toast.LENGTH_LONG).show();
				}

				Intent intent = new Intent();
				intent.setClass(this, SimpleProfileActivity.class);
				intent.putExtra("username", username);
				intent.putExtra("password", password);
				intent.putExtra("isnewuser", true);
				startActivityForResult(intent, REQUEST_EDIT_PROFILE);
				
			} else if (serverResponse == ServerCom.SERVER_ERROR) {
				Toast.makeText(this, "There was an unknown error in the server", Toast.LENGTH_LONG).show();
			} else if (serverResponse == ServerCom.INVALID_USER) {
				Toast.makeText(this, "This username is already in use, please choose another one", Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(this, "There was a fatal error in the server", Toast.LENGTH_LONG).show();
			}
		} else if (requestCode == REQUEST_EDIT_PROFILE) {
			Log.d("SystemLogger", "Done editing profile.");
			this.launchMainActivity();
		}
	}
		
	private static class Util {
		static OnKeyListener filterAlphanumericOnKeyListener = new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				/* Restringe as teclas aos caracteres alfanuméricos;
				 * Este mesmo propósito poderia ser alcanado pela propriedade android:digits dos campos.
				 * 
				 * Return true if the listener has consumed the event, false otherwise.
				 * */
				if (isAlphanumeric(keyCode)
						|| keyCode == KeyEvent.KEYCODE_DEL
						|| keyCode == KeyEvent.KEYCODE_ENTER
						|| keyCode == KeyEvent.KEYCODE_BACK) {
					return false;
				} else {
					return true;
				}
			}
		};
		
		static boolean isAlphanumeric(int keyCode) {
			if ((keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9)
					|| (keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z)) {
				return true;
			} else {
				return false;
			}
		}
	}
}
